class MSBot {
    constructor(options = {}) {
        this.vuid = options.vuid || '';
        this.domain = options.domain || '';
        this.endpoint = options.endpoint || '/api/verify';
        this.challenge = null;
        this.mouseMovements = [];
        this.clickPatterns = [];
        this.startTime = Date.now();
        
        this.initEventListeners();
    }
    
    initEventListeners() {
        // 鼠标移动跟踪
        document.addEventListener('mousemove', (e) => {
            this.mouseMovements.push({
                x: e.clientX,
                y: e.clientY,
                timestamp: Date.now()
            });
            
            // 保持最近100个移动点
            if (this.mouseMovements.length > 100) {
                this.mouseMovements.shift();
            }
        });
        
        // 点击跟踪
        document.addEventListener('click', (e) => {
            this.clickPatterns.push({
                x: e.clientX,
                y: e.clientY,
                timestamp: Date.now()
            });
            
            // 保持最近20个点击点
            if (this.clickPatterns.length > 20) {
                this.clickPatterns.shift();
            }
        });
    }
    
    collectBehaviorData() {
        return {
            mouse_movements: this.mouseMovements,
            click_patterns: this.clickPatterns,
            timing_data: {
                page_load_time: Date.now() - this.startTime,
                time_on_page: Date.now() - this.startTime
            },
            user_agent: navigator.userAgent,
            screen_resolution: `${window.screen.width}x${window.screen.height}`,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            plugins: Array.from(navigator.plugins).map(p => p.name),
            language: navigator.language,
            do_not_track: navigator.doNotTrack === '1' || navigator.doNotTrack === 'yes'
        };
    }
    
    async verify() {
        try {
            // 第一步：获取挑战
            const challengeResponse = await this.sendVerificationRequest({
                vuid: this.vuid,
                domain: this.domain
            });
            
            if (!challengeResponse.success || !challengeResponse.challenge) {
                throw new Error(challengeResponse.error || 'Failed to get challenge');
            }
            
            this.challenge = challengeResponse.challenge;
            
            // 收集行为数据
            const behaviorData = this.collectBehaviorData();
            
            // 第二步：提交验证
            const verificationResponse = await this.sendVerificationRequest({
                vuid: this.vuid,
                domain: this.domain,
                challenge: this.challenge,
                behavior_data: behaviorData
            });
            
            return verificationResponse;
        } catch (error) {
            console.error('Verification error:', error);
            throw error;
        }
    }
    
    async sendVerificationRequest(data) {
        const response = await fetch(this.endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-MSBot-Version': '1.0'
            },
            body: JSON.stringify(data)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    }
    
    static async validateToken(token, vuid, endpoint = '/api/manage') {
        try {
            const response = await fetch(`${endpoint}?action=verify_token`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-MSBot-Version': '1.0'
                },
                body: JSON.stringify({ token, vuid })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('Token validation error:', error);
            throw error;
        }
    }
}

// 导出为全局变量和模块
if (typeof window !== 'undefined') {
    window.MSBot = MSBot;
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = MSBot;
}
